﻿using SSRSURLBuilder.ReportService2005;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SSRSURLBuilder
{
    public partial class Connection : Form
    {
        public ReportingService2005 RSService;

        public Connection()
        {
            InitializeComponent();
        }

        private void tbxPassword_Enter(object sender, EventArgs e)
        {
            tbxPassword.Text = "";
        }

        private void tbxUser_Enter(object sender, EventArgs e)
        {
            tbxUser.Text = "";
        }

        private void tbxPassword_Leave(object sender, EventArgs e)
        {
            tbxPassword.Text = string.IsNullOrEmpty(tbxPassword.Text) ? "123456" : tbxPassword.Text;
        }

        private void tbxUser_Leave(object sender, EventArgs e)
        {
            tbxUser.Text = string.IsNullOrEmpty(tbxUser.Text) ? "DomainName\\UserName" : tbxUser.Text;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbSSRSVersion.SelectedIndex == -1)
                {
                    MessageBox.Show("Please select SSRS Version");
                    return;
                }

                if (string.IsNullOrEmpty(tbxServerAddress.Text))
                {
                    MessageBox.Show("Please enter Server Address");
                    return;
                }
                if (!cbxUseDefaultCreditentals.Checked)
                {
                    if (string.IsNullOrEmpty(tbxUser.Text) || string.IsNullOrEmpty(tbxPassword.Text))
                    {
                        MessageBox.Show("Please enter User Information");
                        return;
                    }
                }

                string RSVersion = cmbSSRSVersion.SelectedItem.ToString();

                var rService = new ReportingService2005
                {
                    Url = tbxServerAddress.Text + @"/ReportService2005.asmx?wsdl",
                    Credentials = cbxUseDefaultCreditentals.Checked ? System.Net.CredentialCache.DefaultCredentials : new NetworkCredential(tbxUser.Text, tbxPassword.Text)
                };

                var reportList = rService.ListChildren(@"/", true);
                RSService = rService;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to Connect to SSRS Server");
            }
        }

        private void cbxUseDefaultCreditentals_CheckedChanged(object sender, EventArgs e)
        {
            tbxUser.Enabled = false;
            tbxPassword.Enabled = false;
        }
    }
}
